package com.lbs.jiepiaisi.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.activity.CommonScanActivity;
import com.lbs.jiepiaisi.activity.PhotoActivity;
import com.lbs.jiepiaisi.base.BaseFragment;
import com.lbs.jiepiaisi.base.ErrorException;
import com.lbs.jiepiaisi.base.ProgressObserver;
import com.lbs.jiepiaisi.base.ResultException;
import com.lbs.jiepiaisi.bean.EqnoLoginBean;
import com.lbs.jiepiaisi.bean.PhotoImgBean;
import com.lbs.jiepiaisi.config.Api;
import com.lbs.jiepiaisi.utils.LocationPerUtil;
import com.lbs.jiepiaisi.utils.PhotoPerUtil;
import com.lbs.jiepiaisi.utils.RxSchedulers;
import com.lbs.jiepiaisi.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.observers.DisposableObserver;

/**
 *
 * 时间：2017/6/16 10:18
 * 作用：拍照平台
 */
@SuppressLint("ValidFragment")
public class PhotoFragment extends BaseFragment {

    public enum UploadImgType {
        UploadImgTypeNormal, // 拍照上传
        UploadImgTypeSupplement // 补拍上传
    }


    //扫描
    private Button scaBtn;
    //输入
    private Button inputBtn;
    private Button loginBtn;

    private LinearLayout ll;

    private EqnoLoginBean mEqnoLoginBean;
    private PhotoImgBean mPhotoImgBean;

    private EditText etEqno;

    private int position;

    private String eqModel;
    //判断从拍照还是从工单进入此页面,正常拍照为true，从工单进入为false
    private boolean isOnlyPai;

    public PhotoFragment() {}

    public PhotoFragment(int position,String eqModel,boolean isOnlyPai) {
        this.eqModel = eqModel;
        this.position = position;
        this.isOnlyPai = isOnlyPai;
    }

    @Override
    public View initView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_photo,null);
        return view;
    }

    @Override
    protected void getExtras(View view) {

    }


    @Override
    protected void findView(View view) {

        ll = (LinearLayout)view.findViewById(R.id.ll_et);

        etEqno = view.findViewById(R.id.et_eqno);

        //扫描
        scaBtn = view.findViewById(R.id.btn_scanning);
        //输入
        inputBtn = view.findViewById(R.id.btn_input);
        scaBtn.setSelected(true);
        inputBtn.setSelected(false);
        scaBtn.setTextSize(23);
        inputBtn.setTextSize(16);
        ll.setVisibility(View.INVISIBLE);

        //etEqno.setText("868120166146164");

        loginBtn = view.findViewById(R.id.btn_photo_login);

    }

    @Override
    protected void setListener(View view) {

        // 扫码登录
        scaBtn.setOnClickListener(v -> {
            scaBtn.setSelected(true);
            inputBtn.setSelected(false);
            scaBtn.setTextSize(23);
            inputBtn.setTextSize(16);
            ll.setVisibility(View.INVISIBLE);
        });

        // 输入设备号登录
        inputBtn.setOnClickListener(v -> {
            scaBtn.setSelected(false);
            inputBtn.setSelected(true);
            scaBtn.setTextSize(16);
            inputBtn.setTextSize(23);
            ll.setVisibility(View.VISIBLE);

        });

        // 登录
        loginBtn.setOnClickListener(v -> {
            if (scaBtn.isSelected()) {
                Intent intent = new Intent(getActivity(), CommonScanActivity.class);
                intent.putExtra("isOnlyPai", isOnlyPai);
                // intent.putExtra(Constant.REQUEST_SCAN_MODE,Constant.REQUEST_SCAN_MODE_ALL_MODE);
                intent.putExtra("position", position);
                intent.putExtra("eqModel", eqModel);
                startActivity(intent);
                Log.e("jjjjj", "扫码");
            }

            if (inputBtn.isSelected()) {
                Log.e("jjjjj", "输入");
                loginByInput();
            }
        });
    }

    public void loginByInput() {
        if (!LocationPerUtil.checkLocationPermission(getActivity())) {
            ToastUtil.show("请打开定位权限");
            return;
        }

        if (!PhotoPerUtil.checkCameraPermission(getActivity())) {
            ToastUtil.show("请打开相机权限");
            return;
        }

        String eqNo = etEqno.getText().toString();

        if (eqNo.length() == 0) {
            ToastUtil.show("设备号不能为空！");
            return;
        }

        /** 设备号登录*/
        Api.getInstance().createService().eqnoLogin(eqNo)
                .compose(RxSchedulers.observableIO2Main(mContext))
                .subscribe(new ProgressObserver<EqnoLoginBean>(mContext,true) {
                    @Override
                    public void onSuccess(EqnoLoginBean result) {
                        // 检查图片数量
                        mEqnoLoginBean = result;
                        loadPhotoInfo();
                    }

                    @Override
                    public void onFailure(ErrorException e) {
                        // code = 1,2,3...
                        switch (e.getCode()){
                            case 1:
                                Log.e("777778","审核中了");
                                ToastUtil.show("信息已提交，正在审核！");
                                break;
                            case 2:
                                ToastUtil.show("该设备号不存在！");
                                break;
                            case 3:
                                ToastUtil.show("信息不全,请在平台完善信息!");
                                break;
                            default:
                                ToastUtil.show(e.getMsg());
                                break;
                        }
                    }
                });
    }

    public void loadPhotoInfo() {
        Api.getInstance().createService()
                .loadImg(mEqnoLoginBean.getResult().getEqId())
                .compose(RxSchedulers.observableIO2Main(mContext))
                .subscribe(new DisposableObserver<Object>() {

                    @Override
                    protected void onStart() {
                        super.onStart();
                    }

                    @Override
                    public void onNext(Object o) {
                        // 补拍上传
                        PhotoImgBean photoImgBean = new PhotoImgBean();
                        PhotoImgBean.InstallInfo installInfo = new PhotoImgBean.InstallInfo();
                        List<PhotoImgBean.FileInfo> files = new ArrayList<>();
                        try {
                            String json = new Gson().toJson(o);
                            Log.e("77777",json);
                            JSONArray result = new JSONObject(json).getJSONArray("result");

                            JSONObject info = result.getJSONObject(0);

                            if (info.length() == 0) {
                                installInfo.setInstaller("");
                                installInfo.setInstallerPhone("");
                                installInfo.setInstallerPosition("");
                            } else {
                                installInfo.setInstaller(info.getString("installer"));
                                installInfo.setInstallerPhone(info.getString("installerPhone"));
                                installInfo.setInstallerPosition(info.getString("installerPosition"));
                            }


                            JSONArray list = result.getJSONArray(1);

                            for (int i = 0; i < list.length(); i++) {
                                JSONObject fileInfoModel = list.getJSONObject(i);
                                PhotoImgBean.FileInfo fileInfo = new PhotoImgBean.FileInfo();
                                fileInfo.setType(fileInfoModel.getInt("type"));
                                files.add(fileInfo);
                            }

                            photoImgBean.setInstallInfo(installInfo);
                            photoImgBean.setFiles(files);

                            mPhotoImgBean = photoImgBean;

                            if (files.size() >= 3) {
                                Log.e("77777","审核中了");
                                ToastUtil.show("信息已提交，正在审核！");
                                return;
                            }

                            ToastUtil.show("登录成功");
                            Intent photoActivity = new Intent(mActivity, PhotoActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("eqnoLoginBean", mEqnoLoginBean);
                            //Log.e("eqnologinBean补拍",mEqnoLoginBean.getResult().getPoint().getPositionTime());
                            bundle.putSerializable("photoImgBean", photoImgBean);
                            bundle.putSerializable("uploadImgType", UploadImgType.UploadImgTypeSupplement);
                            photoActivity.putExtras(bundle);
                            startActivity(photoActivity);

                            Log.e("77777","补拍上传");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof ResultException) {
                            ResultException ex = (ResultException)e;
                            if (ex.getCode() == 1) {
                                Log.e("77777","完整上传");
                                // 完整上传
                                ToastUtil.show("登录成功");
                                Intent photoActivity = new Intent(mActivity, PhotoActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("eqnoLoginBean", mEqnoLoginBean);
                                //Log.e("eqnologinBean",mEqnoLoginBean.getResult().getPoint().getPositionTime()==null?"空的":mEqnoLoginBean.getResult().getPoint().getPositionTime());
//                                bundle.putSerializable("photoImgBean", mPhotoImgBean);
                                bundle.putSerializable("uploadImgType", UploadImgType.UploadImgTypeNormal);
//                                bundle.putSerializable("position", position);
                                photoActivity.putExtras(bundle);
                                startActivity(photoActivity);
                            }
                        }
                    }

                    @Override
                    public void onComplete() {
                        Log.e("66666","onComplete");
                    }
                });
    }
}
